package com.lngsyz.ywtb.pay.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lngsyz.ywtb.biz.service.SystemCompanyService;
import com.lngsyz.ywtb.entity.LoginInfo;
import com.lngsyz.ywtb.entity.biz.AddElecOrder;
import com.lngsyz.ywtb.entity.biz.AddElecOrderInnerSeal;
import com.lngsyz.ywtb.entity.biz.AddPhyOrder;
import com.lngsyz.ywtb.entity.biz.AddPhyOrderInnerSeal;
import com.lngsyz.ywtb.entity.source1.SystemCompany;
import com.lngsyz.ywtb.enumeration.SealMaterial;
import com.lngsyz.ywtb.enumeration.SealMaterialElec;
import com.lngsyz.ywtb.enumeration.SealType;
import com.lngsyz.ywtb.pay.PaySdk;
import com.lngsyz.ywtb.pay.entity.CreateTradeInfoVO;
import com.lngsyz.ywtb.pay.entity.OutCreateTransactionOrderVO;
import com.lngsyz.ywtb.pay.entity.OutQueryHistoricalDataVO;
import com.lngsyz.ywtb.pay.entity.OutRefundOrderHandleDataVO;
import com.lngsyz.ywtb.pay.entity.OutqQueryTransactionOrderDataVO;
import com.lngsyz.ywtb.pay.entity.SealRefundHandleVO;
import com.lngsyz.ywtb.pay.entity.SealTradeDetailsInfoVO;
import com.lngsyz.ywtb.pay.entity.SealTradeMainInfoVO;
import com.lngsyz.ywtb.pay.entity.SealTradeQueryVO;
import com.lngsyz.ywtb.pay.entity.SealTradeTrackVO;
import com.lngsyz.ywtb.util.CommonUtil;
import com.lngsyz.ywtb.util.StringUtil;

import net.sf.json.JSONObject;

@Service
public class PayService {
	
	@Autowired
	SystemCompanyService systemCompanyService;
   
    /**
	 * 查询交易订单结果接口Demo
	 * 
	 * @return
	 */
	public OutqQueryTransactionOrderDataVO queryTransactionOrderResultInterface(String tradeNo) {
		/** 私钥 */
		// String privateKey = "2242D391982B9B0B7D360B24671B6A328E9206500F750FFB57875CFBE04F9180";
		String privateKey = StringUtil.getConfig("config", "PAY_PRIVATE_KEY");
		String appId = StringUtil.getConfig("config", "APP_ID");

		SealTradeTrackVO info = new SealTradeTrackVO();
		// info.setAppId("kn4uwo");
		info.setAppId(appId);
		info.setTradeNo(tradeNo);
		//info.setTradeNo("SL20201101090259260000000009");
		PaySdk paySdk = new PaySdk();
		try {
			String result = paySdk.QueryTransactionOrderResultInterface(info, privateKey);
			System.out.println("订单查询返回信息：" + result);
			OutqQueryTransactionOrderDataVO outqQueryDataVO = new OutqQueryTransactionOrderDataVO();
			outqQueryDataVO = (OutqQueryTransactionOrderDataVO) JSONObject.toBean(JSONObject.fromObject(result),
					OutqQueryTransactionOrderDataVO.class);
			return outqQueryDataVO;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 查询历史交易订单接口Demo
	 * 
	 * @return
	 */
	public OutQueryHistoricalDataVO queryHistoricalTransactionOrders(String tradeNo, String beforeDate, String afterDate) {
		PaySdk paySdk = new PaySdk();
		String privateKey = StringUtil.getConfig("config", "PAY_PRIVATE_KEY");
		String appId = StringUtil.getConfig("config", "APP_ID");

		SealTradeQueryVO vo = new SealTradeQueryVO();
		vo.setAppId(appId);
		vo.setTradeNo(tradeNo);
		vo.setNotBeforeDate(beforeDate);
		vo.setNotAfterDate(afterDate);
//		vo.setTradeNo("SL202011010810232470000000015");
//		vo.setNotBeforeDate("2020-05-20 21:10:23");
//		vo.setNotAfterDate("2020-11-02 08:10:23");
		try {
			String result = paySdk.QueryHistoricalTransactionOrders(vo, privateKey);
			OutQueryHistoricalDataVO outQueryHistoricalDataVO = new OutQueryHistoricalDataVO();
			outQueryHistoricalDataVO = (OutQueryHistoricalDataVO) JSONObject.toBean(JSONObject.fromObject(result),
					OutQueryHistoricalDataVO.class);
			return outQueryHistoricalDataVO;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public OutRefundOrderHandleDataVO sealRefundHandle(String tradeNo, String goodsIds, String reason) throws Exception {
		String privateKey = StringUtil.getConfig("config", "PAY_PRIVATE_KEY");
		String appId = StringUtil.getConfig("config", "APP_ID");
		
		SealRefundHandleVO vo = new SealRefundHandleVO();
		vo.setAppId(appId);
		vo.setTradeNo(tradeNo);
		vo.setGoodsIds(goodsIds);
		vo.setReason(StringUtils.isBlank(reason)?"默认退款原因":reason);
		PaySdk paySdk = new PaySdk();
		try {
			String result = paySdk.RefundOrderHandleInterface(vo, privateKey);
			OutRefundOrderHandleDataVO outRefundOrderHandleDataVO = new OutRefundOrderHandleDataVO();
			outRefundOrderHandleDataVO = (OutRefundOrderHandleDataVO) JSONObject
					.toBean(JSONObject.fromObject(result), OutRefundOrderHandleDataVO.class);
			return outRefundOrderHandleDataVO;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 查询交易订单结果接口Demo
	 * 
	 * @return
	 */
	public CreateTradeInfoVO createSealTransactionOrderInterface(SealTradeMainInfoVO info) throws Exception {
		/** 私钥 */
		// String privateKey = "2242D391982B9B0B7D360B24671B6A328E9206500F750FFB57875CFBE04F9180";
		String privateKey = StringUtil.getConfig("config", "PAY_PRIVATE_KEY");
		String appId = StringUtil.getConfig("config", "APP_ID");
		String publicKey = StringUtil.getConfig("config", "PAY_PUBLIC_KEY");

		PaySdk paySdk = new PaySdk();
		try {
			info.setAppId(appId);
			String result = paySdk.CreateSealTransactionOrderInterface(info, privateKey, publicKey);
			System.out.println("订单创建返回信息：" + result);
			OutCreateTransactionOrderVO outqCreateVO = new OutCreateTransactionOrderVO();
			outqCreateVO = (OutCreateTransactionOrderVO) JSONObject.toBean(JSONObject.fromObject(result),
					OutCreateTransactionOrderVO.class);
			return outqCreateVO.getData();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public SealTradeMainInfoVO packageCreatePayBean(AddPhyOrder addPhyOrder, LoginInfo loginInfo) {
		SystemCompany systemCompany = systemCompanyService.findById(addPhyOrder.getCompanyId());
		SealTradeMainInfoVO rtn = new SealTradeMainInfoVO();
		rtn.setTradeChannel("wxappletpay");
		rtn.setSubject("大连一网通办 | " + loginInfo.getName());
		rtn.setPayOrganizeCode(loginInfo.getInstCode());
		rtn.setPayOrganizeName(loginInfo.getName());
		rtn.setMakeOrganizeCode(systemCompany.getBusinesslicense());
		rtn.setMakeOrganizeName(systemCompany.getName());
		rtn.setKqId(systemCompany.getId());
		rtn.setRemark("测试");
		rtn.setNotifyUrl("");
		List<SealTradeDetailsInfoVO> products = new ArrayList<SealTradeDetailsInfoVO>(); 
		BigDecimal total = BigDecimal.valueOf(0);
		for(AddPhyOrderInnerSeal seal : addPhyOrder.getSeals()) {
			SealTradeDetailsInfoVO product = new SealTradeDetailsInfoVO();
			product.setGoodsId(CommonUtil.createUuid());
			product.setGoodsName("物理 | " + SealType.getNameByKey(seal.getSealType()) + " | " + SealMaterial.getNameByKey(seal.getSealMaterial()));
			product.setQuantity(1);
			product.setPrice(seal.getPrice());
			products.add(product);
			total = total.add(seal.getPrice());
		}
		rtn.setTotalAmount(total);
		rtn.setSealTradeDetailsInfoList(products);
		return rtn;
	}
	
	public SealTradeMainInfoVO packageCreatePayBean(AddElecOrder addElecOrder, LoginInfo loginInfo) {
		SystemCompany systemCompany = systemCompanyService.findById(addElecOrder.getCompanyId());
		SealTradeMainInfoVO rtn = new SealTradeMainInfoVO();
		rtn.setTradeChannel("wxappletpay");
		rtn.setSubject("大连一网通办 | " + loginInfo.getName());
		rtn.setPayOrganizeCode(loginInfo.getInstCode());
		rtn.setPayOrganizeName(loginInfo.getName());
		rtn.setMakeOrganizeCode(systemCompany.getBusinesslicense());
		rtn.setMakeOrganizeName(systemCompany.getName());
		rtn.setRemark("测试");
		rtn.setNotifyUrl("");
		List<SealTradeDetailsInfoVO> products = new ArrayList<SealTradeDetailsInfoVO>();
		BigDecimal total = BigDecimal.ZERO;
		for(AddElecOrderInnerSeal seal : addElecOrder.getSeals()) {
			SealTradeDetailsInfoVO product = new SealTradeDetailsInfoVO();
			product.setGoodsId(CommonUtil.createUuid());
			product.setGoodsName("电子| " + SealType.getNameByKey(seal.getSealType()) + " | " + SealMaterialElec.getNameByKey(seal.getSealMaterial()));
			product.setQuantity(1);
			product.setPrice(seal.getPrice());
			total = total.add(seal.getPrice());
			products.add(product);
		}
		// BigDecimal total = BigDecimal.valueOf(0.03);
		rtn.setTotalAmount(total);
		rtn.setSealTradeDetailsInfoList(products);
		return rtn;
	}
	
	/**
	 * 交易订单关闭
	 * 
	 * @return
	 */
	public boolean closeTradeOrder(SealTradeTrackVO info) throws Exception {
		/** 私钥 */
		// String privateKey = "2242D391982B9B0B7D360B24671B6A328E9206500F750FFB57875CFBE04F9180";
		String privateKey = StringUtil.getConfig("config", "PAY_PRIVATE_KEY");
		String appId = StringUtil.getConfig("config", "APP_ID");
		
		PaySdk paySdk = new PaySdk();
		try {
			info.setAppId(appId);
			boolean result = paySdk.closeTradeOrder(info, privateKey);
			System.out.println("订单关闭：" + info.getTradeNo() + (result ? "成功" : "失败"));
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}
